<?php
class common {
	public $sql = null;
	public $admin = array();
	
	public $def_page = 1;
	public $def_limit = 30;
	
	function __construct() {
		if (empty($this->sql)) {
			global $dbconfig;
			$this->sql = new SQL($dbconfig);
			if ($this->sql->status !== true)
				exit(json(msg(-3, $this->sql->status)));
		}
	}
	
	//检测登录
	function isLogin() {
		if (!isset($_COOKIE['token']) || $_COOKIE['token'] == '') {
			return $this->gotoLogin(1, '您尚未登录！');
		} else if ((!$token = authcode::decode($_COOKIE['token'], LOGIN_KEY)) || (!$info = json_decode($token))) {
			delCookie('token');
			return $this->gotoLogin(2, '登录已过期，请重新登录！');
		} else if ($admin = $this->sql->where("`id` = {$info->id}")->select('admin_user', false)) {
			if ($admin['status'] === 0) {
				delCookie('token');
				return $this->gotoLogin(3, '此账号暂未审核或已禁用！');
			} else if ($info->user !== $admin['user'] || $info->pass !== $admin['pass']) {
				delCookie('token');
				return $this->gotoLogin(4, '登录已过期，请重新登录！');
			}
			$this->admin = $admin;
			return true;
		} else {
			delCookie('token');
			return $this->gotoLogin(5, '登录已过期，请重新登录！');
		}
	}
	
	// 记录日志
	function log($action) {
		if (!empty($this->admin) && !empty($action)) {
			$this->sql->insert('admin_log', array(
				'aid' => $this->admin['id'],
				'module' => isset($_REQUEST['m']) ? $_REQUEST['m'] : '',
				'action' => $action,
				'ip' => getip()
			));
		}
	}
	
    // 转到登录页
	function gotoLogin($code, $msg) {
		return msg($code, $msg, array(
			'top' => ROOT . 'login.html'
		));
	}
	
    // 转到首页
	function gotoHome($code, $msg, $data = array()) {
		$arr = array(
			'top' => ROOT
		);
		if (count($data) > 0)
			$arr = array_merge($arr, $data);
		
		return msg($code, $msg, $arr);
	}
}